import { asyncRoutes, constantRoutes } from '@/router'
import { getAuthPath } from '@/api/user'
import { getToken } from '@/utils/auth' // get token from cookie
import { Message } from 'element-ui'
import Layout from '@/layout'
import store from "@/store/index";

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Note: sub-menu only appear when route children.length >= 1
 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
    noCache: true                if set true, the page will no be cached(default is false)
    affix: true                  if set true, the tag will affix in the tags-view
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */
/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function getRolePath(routes, data) {
  data.forEach(item => {
    const menu = {
      path: item.url === '' ? item.id + '_key' : item.url,
      component: item.type === 1 ? Layout : (resolve) => require([`@/views${item.url}`], resolve),
      redirect: item.redirect,
      children: [],
      name: item.component === "" ? 'menu_' + item.id : item.component,
      meta: {
        title: item.name,
        id: item.id,
        icon: item.icon,
        noCache: item.nocache === 1
      }
    }
    if (item.childPaths !== null) {
      getRolePath(menu.children, item.childPaths)
    }
    //console.log("component---" + item.component);
    routes.push(menu)
  })
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const loadMenuData = []
      // 先查询后台并返回左侧菜单数据并把数据添加到路由
      const userKey = store.state.user.userKey;
      getAuthPath(userKey).then(response => {
        let data = response
        if (response.code !== 20000) {
          Message.error('菜单数据加载异常')
        } else {
          data = response.data.path
          Object.assign(loadMenuData, data)
          getRolePath(asyncRoutes, loadMenuData)
          const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        }
      }).catch(error => {
        console.log(error)
      })
    })
  }
}

// const actions = {
//   generateRoutes({ commit }, roles) {
//     return new Promise(resolve => {
//       let accessedRoutes
//       if (roles.includes('admin')) {
//         accessedRoutes = asyncRoutes2 || []
//       } else {
//         accessedRoutes = filterAsyncRoutes(asyncRoutes2, roles)
//       }
//       commit('SET_ROUTES', accessedRoutes)
//       resolve(accessedRoutes)
//     })
//   }
// }

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
